﻿#pragma once
#include "QD3DWidget.h"
#include <QResizeEvent>
#include <QPaintEvent>


QD3DWidget::QD3DWidget (QWidget* parent, QSize size) : QWidget (parent), _pContext (NULL),
		_isAuto (true)
{
	resize (size);
	setAttribute (Qt::WA_PaintOnScreen, true);
}

QD3DWidget::~QD3DWidget ()
{
	if (_pContext) delete _pContext;
}

void QD3DWidget::paintEvent (QPaintEvent *e)
{
	if (updatesEnabled ())
		_d3DDraw ();
}

void QD3DWidget::resizeEvent (QResizeEvent *e)
{
	if (!initialized ())
		_d3DInit ();
	QD3DContext::lockCur (_pContext);
	resizeD3D (e->size ().width (), e->size ().height ());
	QD3DContext::releaseCur (_pContext);
}

void QD3DWidget::_d3DInit ()
{
	_pContext = new QD3DContext (winId ());
	QD3DContext::lockCur (_pContext);
	initializeD3D ();
	QD3DContext::releaseCur (_pContext);
}

void QD3DWidget::_d3DDraw ()
{
	if (!initialized ())
		_d3DInit ();
	QD3DContext::lockCur (_pContext);
	paintD3D ();
	if (_isAuto)
		swapBuffers ();
	QD3DContext::releaseCur (_pContext);
}

QPaintEngine *QD3DWidget::paintEngine () const
{
	return NULL;
}

bool QD3DWidget::initialized () const
{
	return _pContext != NULL;
}

const QD3DContext *QD3DWidget::getD3DContextPtr () const
{
	return _pContext;
}

QD3DContext *QD3DWidget::getD3DContextPtr ()
{
	return _pContext;
}

void QD3DWidget::swapBuffers ()
{
	// Present the information rendered to the back buffer to the front buffer
	QD3DUtils ().swapBuffers ();
}

void QD3DWidget::closeEvent (QCloseEvent *e)
{
	if (_pContext) delete _pContext;
	_pContext = NULL;
	QWidget::closeEvent (e);
}
